<template>
  <div ref="editor"></div>
</template>

<script setup>
import WangEditor from 'wangeditor';
import AlertMenu from '@/components/wangeditor/AlertMenu.js'
import {uploadFile} from "@/api/upload";
const props = defineProps({
    height:{
      type: Number,
      default: 200
    },
    isvideo:{
      type: Boolean,
      default: false
    },
    content: {
      type: String
    },
    placeholder:{
      type:String,
      default:"请输入内容"
    }
})
const emits = defineEmits(["update:content"])
const editor = ref(null);
let editor_instance = null;

onMounted(() => {
  editor_instance = new WangEditor(editor.value);
  //全局注册菜单
  //WangEditor.registerMenu('alertMenuKey', AlertMenu)
  //WangEditor.registerMenu('formatPainter', FormatPainter)
  // 实例注册菜单
  if(props.isvideo) {
    editor_instance.menus.extend('alertMenuKey', AlertMenu)
    editor_instance.config.menus = editor_instance.config.menus.concat("alertMenuKey")
    editor_instance.config.AlertOnclick = function () {
    }
  }

  // 配置自定义上传图片的回调
  editor_instance.config.customUploadImg = async (files, insert) => {
    for (let i = 0; i < files.length; i++) {
      const formData = new FormData();
      formData.append('file', files[i]);
      // 假设在这里执行图片上传逻辑，并获得上传后的图片链接 resultImageUrl
      const resp = await uploadFile(formData,"systems");
      var baseimg = resp.data.url
      const imgTagWithDirective = `<p class="imgbox"><img class="maya-img" src="${baseimg}"  data-src="${baseimg}" /></p>`;
      editor_instance.cmd.do("insertHtml",imgTagWithDirective)
    }
  };

  // 配置change事件
  editor_instance.config.onchange = function (newHtml) {
    emits('update:content', newHtml);
  };
  // 修改为 500ms
  editor_instance.config.onchangeTimeout = 300;
  editor_instance.config.zIndex = 9999
  // 取消自动 focus
  editor_instance.config.focus = true
  // 设置自动提示
  editor_instance.config.placeholder = props.placeholder
  // 设置编辑区域高度为 500px
  editor_instance.config.height = props.height
  editor_instance.flag = true;
  // 配置菜单栏，设置不需要的菜单
  editor_instance.config.excludeMenus = [
    'emoticon',
    'video'
  ]
  // 创建富文本编辑器
  editor_instance.create();
});


const setHtml = (html)=>{
  editor_instance.flag = true
  //editor_instance.txt.html(html);
}

// 监听父组件传递的content变化，更新编辑器内容
watch(
    () => props.content,
    (newContent) => {
      if(editor_instance.flag) {
        editor_instance.flag = false
        editor_instance.txt.html(newContent);
      }
    }
)

defineExpose({
  setHtml
})

</script>